package cn.wolfcode.p2p.website.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.wolfcode.p2p.base.util.UserContext;

/**
 * 登录检查拦截器
 * 
 * @author wolfcode
 *
 */
@Component
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 如果请求方法有RequireLogin标签并且当前没有登录用户,跳转到login.html
		if (handler != null && handler instanceof HandlerMethod) {
			HandlerMethod hm = (HandlerMethod) handler;
			if (hm.hasMethodAnnotation(RequireLogin.class) && UserContext.getCurrent() == null) {
				response.sendRedirect("/login.html");
				return false;
			}
		}
		// 否则,正常执行
		return super.preHandle(request, response, handler);
	}

}
